/**
 * @file   http.hpp
 * @author wolfhead <wolfhead@wolfhead-laptop>
 * @date   Wed Aug 31 09:54:09 2011
 * 
 * @brief  
 * 
 * 
 */

#ifndef ACAPELLA_UTIL_HTTP_HPP
#define ACAPELLA_UTIL_HTTP_HPP

#include "../string/encode.hpp"
#include "../string/string_util.hpp"

namespace acapella
{
namespace util
{

class Http
{
public:
    template<typename Iterator>
    static void BuildQuery(Iterator begin, Iterator end, std::string& query)
    {
        Encoder<charset::utf8, charset::urlencode> encoder;

        bool first = true;

        for (; begin != end; ++begin)
        {
            if (!first)
            {
                query.append(1, '&');
            }

            query
                .append(encoder.Encode(begin->first))
                .append(1, '=')
                .append(encoder.Encode(begin->second));

            first = false;
        }
    }

    template<typename Iterator>
    static std::string BuildQuery(Iterator begin, Iterator end)
    {
        std::string tmp;
        BuildQuery(begin, end, tmp);
        return tmp;
    }

    template<typename Inserter>
    static void ParseStr(const char * str, Inserter inserter)
    {
        Encoder<charset::urlencode, charset::utf8> encoder;

        std::vector<std::string> params = StringUtil::Explode(str, "&");

        for (size_t i = 0; i != params.size(); ++i)
        {

            if (params[i].empty())
            {
                continue;
            }

            std::vector<std::string> pair =StringUtil::Explode(params[i], "=");
            if (pair.size() != 2)
            {
                continue;
            }

            *inserter++ = std::make_pair(
                encoder.Encode(pair[0]), 
                encoder.Encode(pair[1])
                );
        }
    }

    template<typename Insertor>
    static void ParseStr(const std::string& str, Insertor insertor)
    {
        ParseStr(str.c_str(), insertor);
    }
};


}//namespace util
}//namespace acapella

#endif
